// pages/admin/admin-home/admin-home.js
const { get } = require('../../../utils/request')
const { formatDate, showError, checkLogin } = require('../../../utils/util')

Page({
  data: {
    stats: {
      petCount: 0,
      availablePets: 0,
      adoptionCount: 0,
      pendingAdoptions: 0,
      rescueCount: 0,
      pendingRescues: 0,
      donationAmount: 0,
      donationCount: 0,
      userCount: 0,
      activeUsers: 0,
      noticeCount: 0
    },
    pendingAdoptions: [],
    pendingRescues: [],
    loading: true
  },

  onLoad() {
    // 检查管理员权限
    const app = getApp()
    if (!app.globalData.userInfo || app.globalData.userInfo.role !== 'ADMIN') {
      wx.showModal({
        title: '权限不足',
        content: '您没有管理员权限',
        showCancel: false,
        success: () => {
          wx.navigateBack()
        }
      })
      return
    }

    this.loadDashboardData()
  },

  onShow() {
    this.loadDashboardData()
  },

  // 加载仪表板数据
  loadDashboardData() {
    this.setData({ loading: true })

    Promise.all([
      this.loadStats(),
      this.loadPendingAdoptions(),
      this.loadPendingRescues()
    ]).finally(() => {
      this.setData({ loading: false })
    })
  },

  // 加载统计数据
  async loadStats() {
    try {
      // 加载宠物统计
      const petRes = await get('/pet/list')
      const pets = petRes.data || []
      const availablePets = pets.filter(pet => pet.status === '待领养').length

      // 加载领养申请统计
      const adoptionRes = await get('/adoption/list')
      const adoptions = adoptionRes.data || []
      const pendingAdoptions = adoptions.filter(adoption => adoption.status === '待审核').length

      // 加载救助申请统计
      const rescueRes = await get('/rescue/list')
      const rescues = rescueRes.data || []
      const pendingRescues = rescues.filter(rescue => rescue.status === '待处理').length

      // 加载捐助统计
      const donationRes = await get('/donation/list')
      const donations = donationRes.data || []
      const donationAmount = donations.reduce((sum, donation) => sum + parseFloat(donation.amount || 0), 0)

      // 加载用户统计
      const userRes = await get('/user/all')
      const users = userRes.data || []

      // 加载公告统计
      const noticeRes = await get('/notice/selectAll')
      const notices = noticeRes.data || []

      this.setData({
        'stats.petCount': pets.length,
        'stats.availablePets': availablePets,
        'stats.adoptionCount': adoptions.length,
        'stats.pendingAdoptions': pendingAdoptions,
        'stats.rescueCount': rescues.length,
        'stats.pendingRescues': pendingRescues,
        'stats.donationAmount': donationAmount.toFixed(0),
        'stats.donationCount': donations.length,
        'stats.userCount': users.length,
        'stats.activeUsers': users.length, // 简化处理，实际可以根据最后登录时间计算
        'stats.noticeCount': notices.length
      })
    } catch (err) {
      console.error('加载统计数据失败:', err)
    }
  },

  // 加载待审核领养申请
  async loadPendingAdoptions() {
    try {
      const res = await get('/adoption/list', { status: '待审核' })
      const adoptions = (res.data || []).slice(0, 3) // 只显示前3条
      
      adoptions.forEach(item => {
        item.createTime = formatDate(item.createTime)
      })

      this.setData({
        pendingAdoptions: adoptions
      })
    } catch (err) {
      console.error('加载待审核领养申请失败:', err)
    }
  },

  // 加载待处理救助申请
  async loadPendingRescues() {
    try {
      const res = await get('/rescue/list', { status: '待处理' })
      const rescues = (res.data || []).slice(0, 3) // 只显示前3条
      
      rescues.forEach(item => {
        item.createTime = formatDate(item.createTime)
      })

      this.setData({
        pendingRescues: rescues
      })
    } catch (err) {
      console.error('加载待处理救助申请失败:', err)
    }
  },

  // 快速操作跳转
  goToPetManage() {
    wx.navigateTo({
      url: '/pages/admin/pet-manage/pet-manage'
    })
  },

  goToAdoptionManage() {
    wx.navigateTo({
      url: '/pages/admin/adoption-manage/adoption-manage'
    })
  },

  goToRescueManage() {
    wx.navigateTo({
      url: '/pages/admin/rescue-manage/rescue-manage'
    })
  },

  goToUserManage() {
    wx.navigateTo({
      url: '/pages/admin/user-manage/user-manage'
    })
  },

  goToNoticeManage() {
    wx.navigateTo({
      url: '/pages/admin/notice-manage/notice-manage'
    })
  },

  addPet() {
    wx.navigateTo({
      url: '/pages/admin/pet-form/pet-form'
    })
  },

  // 审核领养申请
  reviewAdoption(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/admin/adoption-review/adoption-review?id=${id}`
    })
  },

  // 处理救助申请
  handleRescue(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/admin/rescue-review/rescue-review?id=${id}`
    })
  }
})
